<template>
  <div class="file-deteils">
    <van-nav-bar :border="false" placeholder fixed>
      <template #left>
        <svg-icon name="arrows" @click="topReturnClick" />
      </template>
      <template #title>
        <span class="contract-title">文件详情</span>
      </template>
    </van-nav-bar>
    <div class="file-message">
      <div class="title">
        <span class="file-name">人事文件.PDF</span>
        <svg-icon
          name="file-download"
          className="svg-icon-name"
          @click="downloadContractFileClick"
        />
      </div>
      <div class="file-state">
        <div>
          状态:
          <span class="contract-state">{{
            currentRate === 100 ? '签署完成' : '签约中'
          }}</span>
        </div>
        <span v-show="showArrow" @click="showArrow = false"
          >展开<van-icon name="arrow-down"
        /></span>
      </div>
      <div class="file-content" v-show="!showArrow">
        <div class="content">
          <canvas id="my-canvas" width="100" height="100"></canvas>
          <div class="box-right">
            <span>发件方: {{ contractBaseInfo.sponsorName }}</span>
            <span>发起人: {{ contractBaseInfo.sponsorMobile }}</span>
            <span>发起时间: {{ contractBaseInfo.createTime }}</span>
            <span>截止时间: {{ contractBaseInfo.signingEndTime }}</span>
          </div>
        </div>
        <div
          class="arrow-up-click"
          v-show="!showArrow"
          @click="showArrow = true"
        >
          收起<van-icon name="arrow-up" />
        </div>
      </div>
    </div>
    <div class="stripe">参与方</div>
    <div class="participant">
      <template v-for="item in signingList" :key="item.id">
        <div class="participant-box">
          <span class="org-name">{{ item.orgName ?? '个人' }}</span>
          <div class="user-name">
            <div class="user-left">
              <span class="name">{{ item.userName }}</span>
              <span class="name">{{ item.userMobile }}</span>
              <span
                class="name"
                :style="{ color: item.signerState === 1 ? '' : '#2489f2' }"
                >{{ item.signerState === 1 ? '已签署' : '未签署' }}</span
              >
            </div>
            <span>{{ item.signTime }}</span>
          </div>
        </div>
      </template>
    </div>
    <div class="stripe" v-if="recipientList.length">抄送方</div>
    <div class="copy">
      <template v-for="item in recipientList">
        <div class="content">
          <span>{{ item.orgName }}</span>
          <span>{{ item.operatorContact }}</span>
        </div>
      </template>
    </div>
    <div class="stripe">签约文件</div>
    <div class="sign-file">
      <van-image
        class="file-image"
        width="150"
        height="100"
        :src="contractImageList[0] ?? ''"
        @click="signingFileClick"
      />
      <div class="file-name">{{ signingFileImageData.fileName }}</div>
      <div class="page-number">共{{ signingFileImageData.filePages }}页</div>
    </div>
    <div class="stripe" v-if="associateImageList.length">附属文件</div>
    <div class="sign-file" v-if="associateImageList.length">
      <van-image
        class="file-image"
        width="150"
        height="100"
        :src="associateImageList[0] ?? ''"
        @click="associateFileClick"
      />
      <div class="file-name">{{ associateImageData.fileName }}</div>
      <div class="page-number">共{{ associateImageData.filePages }}页</div>
    </div>
    <van-divider :style="{ padding: '0 100px', margin: '0' }" :hairline="false"
      >没有更多了</van-divider
    >
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, watchEffect } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ImagePreview, Dialog } from 'vant'

import {
  getContractAllInfo,
  getContractBase64Img,
  getContractFileDownload,
  getSigningCompletion
} from '@/api/contract'
export default defineComponent({
  setup() {
    const router = useRouter()
    const route = useRoute()
    const showArrow = ref(true)
    // 返回按钮
    const topReturnClick = () => {
      router.push('/home-page')
    }
    // 进度条
    const currentRate = ref(0)
    const changeContractSigningCompletion = async () => {
      const params = {
        contractId: route.query.contractId as string
      }
      const res = await getSigningCompletion(params)
      if (res.code !== '0') return
      currentRate.value = res.data.progressPercentage * 100
    }
    const drawCricle = (percent: number) => {
      const canvas: HTMLCanvasElement = document.querySelector('#my-canvas')!
      const ctx = canvas.getContext('2d')!
      ctx.clearRect(0, 0, 100, 100) //清空所有的内容
      ctx.beginPath()
      ctx.lineWidth = 4
      ctx.lineCap = 'round'
      ctx.arc(
        40,
        40,
        37,
        Math.PI * 0.7,
        Math.PI * (0.7 + (1.6 * percent) / 100)
      )
      //绘制渐变色
      var g = ctx.createLinearGradient(0, 0, 180, 0)
      g.addColorStop(0, '#2EB0FE')
      g.addColorStop(1, '#248AF2')
      ctx.strokeStyle = g
      ctx.stroke()
      // 填充文字
      ctx.font = '600 14px PingFangSC'
      ctx.fillStyle = '#000'
      ctx.textAlign = 'center'
      ctx.textBaseline = 'middle'
      ctx.fillText(percent + '%', 41, 35)
      ctx.fillStyle = '#999'
      ctx.font = '11px PingFangSC'
      ctx.fillText('签约完成度', 41, 55)
    }
    watchEffect(() => {
      if (!showArrow.value) {
        let initNumber = 0
        setInterval(() => {
          if (initNumber <= currentRate.value) {
            drawCricle(initNumber)
            initNumber++
          }
        }, 20)
      }
    })

    // 获取合同所有信息
    const signingList = ref<any>([]) // 签署方
    const recipientList = ref<any>([]) // 抄送方
    const contractBaseInfo = ref<any>({}) // 合同信息
    const signingFileImageData = reactive({
      // 签约文件
      filePages: 0,
      pageNumber: 1,
      filePath: '',
      fileName: ''
    })

    const changeContractAllList = async () => {
      const params = {
        contractId: route.query.contractId as string
      }
      const res = await getContractAllInfo(params)
      if (res.code !== '0') return
      contractBaseInfo.value = res.data.contractBaseInfo
      signingList.value = res.data.signatoryInfoList
      recipientList.value = res.data.recipientInfoList
      // 显示第一个合同
      const file = res.data.signingFileInfoList[0]
      signingFileImageData.filePages = file.filePages
      signingFileImageData.filePath = file.filePath
      signingFileImageData.fileName = file.fileName
    }
    // 获取文件图片
    const contractImageList = ref<any>([]) // 文件图片
    const changeContractImageList = async () => {
      for (
        let i = signingFileImageData.pageNumber;
        i <= signingFileImageData.pageNumber;
        i++
      ) {
        const res = await getContractBase64Img({
          filePath: signingFileImageData.filePath,
          pageNum: i
        })
        if (res.code !== '0') return
        contractImageList.value.push(`data:image/png;base64,${res.data}`)
      }
      signingFileImageData.pageNumber++
    }
    // 预览签署合同
    const signingFileClick = async () => {
      if (contractImageList.value.length < signingFileImageData.filePages) {
        await changeContractImageList()
      }
      ImagePreview({
        images: [...contractImageList.value],
        startPosition: 0,
        closeable: true,
        onChange() {
          signingFileClick()
        }
      })
    }

    // 获取关联文件信息
    const associateImageList = ref<any>([]) // 关联文件图片
    const associateImageData = reactive({
      filePages: 0,
      pageNumber: 1,
      filePath: '',
      fileName: ''
    })
    const changeAssociateContractList = async () => {
      const params = {
        contractId: contractBaseInfo.associateId
      }
      const res = await getContractAllInfo(params)
      if (res.code !== '0') return
      const file = res.data.signingFileInfoList[0]
      associateImageData.filePages = file.filePages
      associateImageData.filePath = file.filePath
      associateImageData.fileName = file.fileName
    }
    // 获取关联文件图片
    const changeAssociateImageList = async () => {
      for (
        let i = associateImageData.pageNumber;
        i <= associateImageData.pageNumber;
        i++
      ) {
        const res = await getContractBase64Img({
          filePath: associateImageData.filePath,
          pageNum: i
        })
        if (res.code !== '0') return
        associateImageList.value.push(`data:image/png;base64,${res.data}`)
      }
      associateImageData.pageNumber++
    }
    // 预览关联合同
    const associateFileClick = async () => {
      if (contractImageList.value.length < signingFileImageData.filePages) {
        await changeAssociateImageList()
      }
      ImagePreview({
        images: [...contractImageList.value],
        startPosition: 0,
        closeable: true,
        onChange() {
          associateFileClick()
        }
      })
    }

    // 合同下载
    const downloadContractFileClick = () => {
      Dialog.confirm({
        title: '是否下载文件?'
      })
        .then(async () => {
          const params = {
            contractId: route.query.contractId as string
          }
          const res = await getContractFileDownload(params)
          if (res.code !== '0') return
          const url = `data:image/png;base64,${res.data}`
          const parts = url.split(';base64,')
          const contentType = parts[0].split(':')[1]
          const raw = window.atob(parts[1])
          const rawLength = raw.length
          const uInt8Array = new Uint8Array(rawLength)
          for (let i = 0; i < rawLength; ++i) {
            uInt8Array[i] = raw.charCodeAt(i)
          }
          const hrefURL = new Blob([uInt8Array], {
            type: contentType
          })
          const link = document.createElement('a')
          const evt = document.createEvent('HTMLEvents')
          evt.initEvent('click', true, true)
          const contractName = associateImageData.fileName
          link.download = contractName || ''
          link.href = URL.createObjectURL(hrefURL)
          link.click()
        })
        .catch(() => {})
    }
    // 数据初始化
    const init = async () => {
      await changeContractAllList()
      await changeContractImageList()
      if (contractBaseInfo.associateId) {
        // 有关联合同信息
        await changeAssociateContractList()
        await changeAssociateImageList()
      }
      await changeContractSigningCompletion()
    }
    init()
    return {
      currentRate,
      showArrow,
      contractBaseInfo,
      signingList,
      recipientList,
      signingFileImageData,
      associateImageData,
      associateImageList,
      contractImageList,
      topReturnClick,
      signingFileClick,
      associateFileClick,
      downloadContractFileClick
    }
  }
})
</script>

<style scoped lang="less">
.file-deteils {
  width: 100%;
  height: 100%;
  .contract-title {
    font-size: 17px;
    color: #101010;
    font-weight: 700;
  }
  .file-message {
    padding: 22px 22px 0 22px;
    background-color: #fff;
    .title {
      display: flex;
      justify-content: space-between;
      .file-name {
        font-size: 18px;
        color: #101010;
        font-weight: 700;
      }
      .svg-icon-name {
        width: 20px;
        height: 20px;
      }
    }
    .file-state {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px 0 20px;
      font-size: 13px;
      color: #999;
      .contract-state {
        padding: 0 8px;
        color: #2489f2;
      }
    }
    .file-content {
      height: 170px;
      background-color: #fff;
      .content {
        box-sizing: border-box;
        height: 120px;
        background-color: #f6f6f6;
        display: flex;
        padding: 10px 10px 0;
        .box-left {
          height: 100%;
          width: 35%;
        }
        .box-right {
          display: flex;
          flex-direction: column;
          justify-content: space-evenly;
          height: 100%;
          width: 65%;
          color: #666;
          font-size: 12px;
        }
      }
      .arrow-up-click {
        height: calc(100% - 120px);
        display: flex;
        justify-content: flex-end;
        align-items: center;
        font-size: 13px;
        color: #999;
      }
    }
  }
  .stripe {
    height: 32px;
    line-height: 32px;
    padding: 0 22px;
    font-size: 13px;
    color: #999999;
  }
  .participant {
    background-color: #fff;
    .participant-box {
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      justify-content: space-evenly;
      height: 82px;
      margin: 0 22px;
      padding: 8px 0;
      border-bottom: 1px solid #e5e5e5;
      .org-name {
        font-size: 15px;
        color: #101010;
      }
      .user-name {
        display: flex;
        justify-content: space-between;
        font-size: 13px;
        color: #999;
        .name {
          padding-right: 8px;
        }
      }
    }
    .participant-box:last-child {
      border-bottom: none;
    }
  }
  .copy {
    background-color: #fff;
    .content {
      height: 50px;
      margin: 0 22px;
      line-height: 50px;
      border-bottom: 1px solid #e5e5e5;
      font-size: 13px;
      color: #999;
      span {
        padding-right: 8px;
      }
    }
    .content:last-child {
      border-bottom: none;
    }
  }
  .sign-file {
    background-color: #fff;
    padding: 14px 22px;
    .file-image {
      border: 1px solid #e0e0e0;
    }
    .file-name {
      font-size: 13px;
      color: #101010;
    }
    .page-number {
      padding-top: 8px;
      font-size: 11px;
      color: #999999;
    }
  }
}
</style>
